<?php

namespace App\Store\Controllers\Account;

use App\Admin\Models\AdminUser;
use App\Admin\Models\SiteCompany;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Store\Models\Account\Account;
use App\Common\Services\Store\Common;
use App\Store\Validate\Account\Account as ValidateAccountAccount;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Account\AccountRole;
use App\Store\Models\Account\SiteStore;
use App\Store\Services\AccountMenuRole;
use Illuminate\Support\Facades\Redis;

class AccountController extends Controller
{

    /**
     * 获取用户详情
     */
    public function getinfo(Request $request)
    {
        $info = Common::getCurrentAccountinfo($request);
        $info = Account::where(['id' => $info['id']])->first();
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }

    /**
     * 编辑个人信息
     */
    public function editinfo(Request $request)
    {
        $info = Common::getCurrentAccountinfo($request);
        $req_data = $request->only(['real_name', 'user_img', 'phone_no','salary', 'mobile']);
        $data=['update_at'=>time()];
        foreach($req_data as $key=>$val){
            if($val!=''){
                $data[$key]=$val;
            }
        }
        Account::where(['id' => $info['id']])->update($data);
        return response()->json(['code' => '000', 'msg' => '编辑成功']);
    }

    public function getshoppingaccount(Request $request){
        $info = Common::getCurrentAccountinfo($request);
        $list = Account::where(['cp_id' => $info['cp_id']])->whereIn('type',[1,2])->get()->toArray();
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['list' => $list]]);
    }

    public function getcurrentstoreshoppingaccount(Request $request){
        $info = Common::getCurrentAccountinfo($request);
        $query=Account::query()->where(['cp_id' => $info['cp_id']])->whereIn('type',[1,2])->where('is_del',1);
        $store_ids = $info['store_ids'];
        if($store_ids){//权限控制
            if(is_array($store_ids)){//获取当前权限下的门店
                $query->whereIn('store_ids',$store_ids);
            }
            if(is_numeric($store_ids) && intval($store_ids)>0){//获取当前门店下的列表
                $query->where('store_ids', intval($store_ids));
            }
        }
        $list = $query->get()->toArray();
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['list' => $list]]);
    }

    /**
     * 获取管理员账号列表
     */
    public function getlist(Request $request){
        $request->getaccountwithoutdepartment=1;
        $list = Account::getList($request);

        //print_r($list);exit;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        foreach($list['list'] as &$val){
            if($val['store_ids']==''){
                $val['store_listinfo']=SiteStore::where(['cp_id'=>$cp_id])->select(['id','store_name'])->get()->toArray();
            }else{
                if(is_numeric($val['store_ids']) && intval($val['store_ids'])>0){
                    $val['store_listinfo']=SiteStore::where(['id'=>intval($val['store_ids']),'cp_id'=>$cp_id])->select(['id','store_name'])->get()->toArray();
                }else{
                    $val['store_listinfo']=SiteStore::whereIn('id',explode(',',$val['store_ids']))->where(['cp_id'=>$cp_id])->select(['id','store_name'])->get()->toArray();
                }
            }
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 获取管理员账号详情
     */
    public function getinfobyid(Request $request){
        $info = Account::getInfo($request);
        if(!$info){
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }
    /**
     * 编辑管理员账号信息
     */

    public function editinfobyid(Request $request)
    {
        $req_data = $request->only(['id','type','type_alias', 'store_ids', 'account_name','real_name', 'user_no','is_band_userimg','user_img','is_order_msg','is_sendorder_msg',
        'phone_no','mobile','status','entry_at','salary','remark']);

        $Validate = new ValidateAccountAccount('edit');

        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $info = Account::query()
            ->where('id',$req_data['id'])
            ->first();

        if(!$info){
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        if(in_array($req_data['type'],[1,2])){
            if(!( isset($req_data['store_ids']) && is_numeric($req_data['store_ids']) && intval($req_data['store_ids'])>0)){
                return response()->json(['code' => '001', 'msg' => '店长店员请选择单门店']);
            }
        }

        $isexist = Account::where([['id','<>',$request->id],['account_name', $req_data['account_name']],['is_del',1]])->first();

        if ($isexist) {
            return response()->json(['code' => '001', 'msg' => '账号不允许重复']);
        }

        $isexist = AdminUser::where([['username', $req_data['account_name']], ['type', 1]])->first();

         if ($isexist) {
             return response()->json(['code' => '001', 'msg' => '账号信息不可与超管信息相同']);
         }

        foreach($req_data as $key=>$val){
            if ($val == '' || $val == 0) {
                if($info->$key){
                    $req_data[$key]=is_numeric($info->$key)?0:'';
                }else{
                    unset($req_data[$key]);
                }

            }
        }
        $data=$req_data;
        $data['update_at']=time();
        $data['entry_at']=isset($data['entry_at'])?strtotime($data['entry_at']):0;

        Account::where(['id' => $info->id])->update($data);
        //重置后需重置账号登陆状态
        Common::cleartokenkey($info->id);
        Common::cleartokenkeybywxapp($info->id);
        return response()->json(['code' => '000', 'msg' => '编辑成功']);
    }

    /**
     * 新增管理员账号
     */
    public function dopostadd(Request $request)
    {
        $req_data = $request->only(['type','type_alias', 'store_ids', 'account_name','real_name', 'user_no','is_band_userimg','user_img','is_order_msg','is_sendorder_msg',
        'phone_no','mobile','status','entry_at','salary','remark']);
        $Validate = new ValidateAccountAccount();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        if(in_array($req_data['type'],[1,2])){
            if(!( isset($req_data['store_ids']) && is_numeric($req_data['store_ids']) && intval($req_data['store_ids'])>0)){
                return response()->json(['code' => '001', 'msg' => '店长店员请选择单门店']);
            }
        }

        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);

        //培训账号
        if ($req_data['type'] == 11) {
            $company = SiteCompany::where(['id' => $cp_id])->first();
            if ($company->training_min == 0 && $company->training_max == 0) {
                return response()->json(['code' => '001', 'msg' => '培训账号，需要在对应的公司设置上下限']);
            }
        }

        //判断账号是否重复
        $isexist = Account::where([['account_name', $req_data['account_name']],['is_del', 1]])->first();
        if ($isexist) {
            return response()->json(['code' => '001', 'msg' => '账号不允许重复']);
        }

        $isexist = AdminUser::where([['username', $req_data['account_name']], ['type', 1]])->first();
        if ($isexist) {
            return response()->json(['code' => '001', 'msg' => '账号信息不可与超管信息相同']);
        }

//        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
//        if($accountinfo['type']==9 && $accountinfo['is_show_manger']==1 && $req_data['type'] == 9){
//            return response()->json(['code' => '001', 'msg' => '无权限']);
//        }

        $data = $req_data;
        foreach ($data as $key => $val) {
            if ($val == '' || $val == 0) {
                unset($data[$key]);
            }
        }
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $data['cp_id']=$cp_id;
        $data['password']=MD5(MD5('zhuxiaobao_' . env('ACCOUNT_DEF_PWD')));
        $data['entry_at']=isset($data['entry_at'])?strtotime($data['entry_at']):0;
        $data['create_at']=time();
        $data['update_at']=time();
        $account_id=Account::create($data)->id;
        AccountMenuRole::setAccountRole($account_id,$req_data['type']);
        return response()->json(['code' => '000', 'msg' => '新增账号成功']);


    }

    public function resetpassword(Request $request)
    {
        //重置后需重置账号登陆状态
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = Account::where([['id', $id],['cp_id',$cp_id],['is_del',1]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $password = MD5(MD5('zhuxiaobao_' . env('ACCOUNT_DEF_PWD')));
        Account::where([['id', $info->id]])->update(['password' => $password, 'update_at' => time()]);

        //重置后需重置账号登陆状态
        Common::cleartokenkey($info->id);
        Common::cleartokenkeybywxapp($info->id);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }
    /**
     * 删除管理员账号
     */
    public function dodel(Request $request)
    {
        //重置后需重置账号登陆状态
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = Account::where([['id', $id],['cp_id',$cp_id],['is_del',1]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if((int)$info['is_super']==1){

            return response()->json(['code' => '001', 'msg' => '系统分配的账号不能删除']);
        }
        Account::where([['id', $info->id]])->update(['is_del' => 2, 'del_at' => time()]);
        //重置后需重置账号登陆状态
        Common::cleartokenkey($info->id);
        Common::cleartokenkeybywxapp($info->id);
        return response()->json(['code' => '000', 'msg' => '删除成功']);
    }

    //获取公司信息
    public function getcurrentcompany(Request $request)
    {

        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info=SiteCompany::where(['id'=>$cp_id])->first();
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => ['info'=>$info]]);
    }

    //修改培训账号上下限
    public function resetcompany(Request $request)
    {
        $req_data = $request->only(['training_min','training_max']);
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);

        $data=['training_min'=>$req_data['training_min'],'training_max'=>$req_data['training_max']];
        SiteCompany::where(['id'=>$cp_id])->update($data);

        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 获取权限
     */

     public function getruleinfo(Request $request)
     {
         //获取菜单列表以及管理员已设置的权限
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = Account::where([['id', $id],['cp_id',$cp_id],['is_del',1]])->first();
         if (!$info) {
             return response()->json(['code' => '001', 'msg' => '参数错误']);
         }
//         if( $info->type == 9){
//            return response()->json(['code' => '001', 'msg' => '管理员不可设置权限']);
//        }
         $rule_info = AccountRole::where(['account_id' => $id])->first();
         $menu_ruleinfo = json_decode($rule_info->menu_ruleinfo, true);
         return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $menu_ruleinfo]);
     }

     /**
      * 设置权限
      */
     public function dopostrule(Request $request)
     {

         //设置权限后，需要对比用户现有权限
         $id = $request->id ?? 0;
         $menu_ruleinfo = is_array($request->menu_ruleinfo) ? $request->menu_ruleinfo : (is_array(json_decode($request->menu_ruleinfo, true)) ? json_decode($request->menu_ruleinfo, true) : []);
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = Account::where([['id', $id],['cp_id',$cp_id],['is_del',1]])->first();
         if (!$info) {
             return response()->json(['code' => '001', 'msg' => '参数错误']);
         }
         if (count($menu_ruleinfo) <= 0) {
             return response()->json(['code' => '001', 'msg' => '权限菜单信息有误']);
         }


//        if( $info->type == 9){
//            return response()->json(['code' => '001', 'msg' => '管理员不可设置权限']);
//        }
         $menu_ruleinfo = json_encode($menu_ruleinfo);
         AccountRole::where(['account_id' => $id])->update(['menu_ruleinfo' => $menu_ruleinfo]);
         Redis::set('account_user_menulist_Account_' . $id, $menu_ruleinfo);

         //重置用户现有权限
         return response()->json(['code' => '000', 'msg' => '操作成功']);
     }


     public function dochangewxapploginstatus(Request $request)
    {
        //重置后需重置账号登陆状态
        $id = $request->id ?? 0;

        $is_wxapp_login = intval($request->is_wxapp_login)==1 ?1:2;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = Account::where([['id', $id],['cp_id',$cp_id],['is_del',1]])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        Account::where([['id', $info->id]])->update(['is_wxapp_login' => $is_wxapp_login, 'update_at' => time()]);
        Common::cleartokenkeybywxapp($info->id);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

}
